import socket
import threading

# 本地IP和端口
localIP = "192.168.0.108"
localPort = 8888

# 远程IP和端口（ESP32的IP和端口）
remoteIP = "192.168.0.110"
remotePort = 8888

# 创建UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((localIP, localPort))

# 监听UDP数据包的线程函数
def listen_thread():
    while True:
        # 从UDP套接字接收数据
        data, addr = sock.recvfrom(1024)
        try:
            _data = data.decode()
        except Exception as e:
            _data = str(e)
        print("\nReceived packet from {}:\n{}\nEnter message to send:".format(addr[0], _data), end="")

# 接收用户输入消息的线程函数
def input_thread():
    while True:
        # 通过input()函数接收用户输入的消息
        message = input("Enter message to send: ")
        # 发送数据到ESP32
        sock.sendto(message.encode(), (remoteIP, remotePort))
def listen_forever():
    while True:
        # 从UDP套接字接收数据
        data, addr = sock.recvfrom(1024)
        print("\nReceived packet from {}: {}\nEnter message to send:".format(addr[0], data.decode()))

    # # 发送数据到ESP32
    # message = "Hello, ESP32!"
    # sock.sendto(message.encode(), (remoteIP, remotePort))

def start_two_thread():
    # 创建并启动监听线程和输入线程
    threading.Thread(target=listen_thread).start()
    threading.Thread(target=input_thread).start()

if __name__ == "__main__":
    start_two_thread()